package com.wzq.backend.config;

import com.alibaba.fastjson.JSON;
import com.wzq.backend.system.AuthenticationAccessDeniedHandler;
import com.wzq.backend.system.MyAccessDecisionManager;
import com.wzq.backend.system.MyFilterInvocationSecurityMetadataSource;
import com.wzq.starter.Response;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.annotation.Resource;
import java.io.PrintWriter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private MyAccessDecisionManager myAccessDecisionManager;
    @Resource
    private MyFilterInvocationSecurityMetadataSource myFilterInvocationSecurityMetadataSource;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    public <O extends FilterSecurityInterceptor> O postProcess(
                            O fsi) {
                        fsi.setSecurityMetadataSource(myFilterInvocationSecurityMetadataSource);
                        fsi.setAccessDecisionManager(myAccessDecisionManager);
                        return fsi;
                    }
                })
                .and()
                .csrf().disable()
                .headers().frameOptions().disable()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll() //登录页面用户任意访问
                .failureHandler((httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
                        IOUtils.write(JSON.toJSONString(Response.failed("用户名或密码错误!")), out);
                    } else if (e instanceof DisabledException) {
                        IOUtils.write(JSON.toJSONString(Response.failed("账户被禁用，登录失败，请联系管理员!")), out);
                    } else {
                        IOUtils.write(JSON.toJSONString(Response.failed("登录失败")), out);
                    }
                }).successHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    IOUtils.write(JSON.toJSONString(Response.success("登陆成功！")), out);
                }).and().logout().permitAll().and().csrf().disable().exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler);
    }

    @Override
    public void configure(WebSecurity web) {
        // 忽略URL
        web.ignoring().antMatchers("/**/*.js", "/**/*.css", "/**/*.map", "/**/*.html",
                "/**/*.png", "/**/favicon.ico", "/**/*.gif", "/**/*.woff", "/**/*.woff2", "/**/*.svg");
    }
}
